//
//  MainTabBarController.swift
//  kz
//
//  Created by Tech_001 on 8/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit

class MainTabBarController: UITabBarController,UITabBarControllerDelegate,UIGestureRecognizerDelegate{
    
//    var tabMineMainTableViewController:TabMineMainTableViewController?
    var tabSupportViewTwoController:TabSupportViewTwoController?
    var _loadViews: [UIView?] = []
    var matchedData: [[String:Any]] = [[:]]
    var matchedCellData: [UIView:[String:Any]] = [:]
    var effecView: KefuView?
    var maintainData: [UIView:Bool] = [:]
    var gameAlertView: CsAlertView?
    var mainTabBarController: MainTabBarController?
    var csUrl: String?
    var atcUrl: String?
    var _loadView: UIView?
       var bufWindows: [UIWindow] = []    //缓存window
     var delay: Double = 2.0  //延迟时间
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    override var prefersStatusBarHidden: Bool {
        return self.isStatusBarHidden
    }
   func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        switch tabBarController.tabBar.tag {
        case 0:

              ToolHelper.statisticsPage(pageName: "首页-底部导航-首页")
            return true
    
        case 1:
//            ToolHelper.statisticsPage(pageName: "导航：游戏")
//            let goNext = GameHomeViewController()
//              goNext.hidesBottomBarWhenPushed = true
//            let nave = self.childViewControllers[self.selectedIndex] as!UINavigationController
//              nave.pushViewController(goNext, animated: true)
             ToolHelper.statisticsPage(pageName: "首页-底部导航-游戏")
             if(UserHelper.getLoginStatus()){
                return true
             }else{
                setRootLoginVC()
                return false
            }
       
        case 2:
            self._loadView = UIHelper.initLoadView(self, withMessage: "加载中...")
            let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
           window.addSubview(self._loadView!)
            RequestHelper.post(atPath: "/ClientsAPIs/Comm100Api",withData:Dictionary(), withCompletion: { (data) in
                var dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                //点击弹窗显示客服
                DispatchQueue.main.async {
                    let success = dataArray?["success"] as? Bool ?? false
                    
                    if success  == true{
                       let data = dataArray?["data"] as? [String : Any] ?? [:]
                       let topDict = data["top"] as? [String : Any] ?? [:]
                        let topStatus = topDict["status"] as? Int ?? 0
                        if topStatus == 0{//不显示

                        }else{//显示

                        }
//                        self._loadView?.removeFromSuperview()
//                        PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: true)
                        NetWorkRequest(API.checkAccessRight(url: "9a28015"), completion: { (responseData,statusCode,strData) -> (Void) in
                            DispatchQueue.main.async {
                                self._loadView?.removeFromSuperview()
                                let dataDict = responseData["data"].dictionary
                                let responseDict =  dataDict?["response"]?.dictionary
                                let c = responseDict?["c"]?.int ?? -1
                                let d = responseDict?["d"]?.dictionary
                                let m = responseDict?["m"]?.stringValue
                                if c == 0{
                                    let phoneRecallAccessResult = d?["phoneRecallAccessResult"]?.boolValue
                                    if phoneRecallAccessResult == false{ //没权限
                                         PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                                    }else{//有权限
                                         PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: true)
                                    }
                                }else{
                                    UIHelper.alertSimpleMessage(about: "\(m ?? "")", withDescription: "", in: self)
                                    PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                                }
                            }


                        }, failed: { (faildInfo,reCode,msg) -> (Void) in
                            DispatchQueue.main.async {
                                self._loadView?.removeFromSuperview()
                                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                                PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                                }
                        }) { () -> (Void) in
                            DispatchQueue.main.async {
                                self._loadView?.removeFromSuperview()
                               UIHelper.alertSimpleMessage(about: "权限信息请求异常!", withDescription: "", in: self)
                                PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                            }
                        }
//
 //                       self.alertCsShow(dict: dataArray?["data"] as? [String : Any] ?? [:])
                    }else{
                        self._loadView?.removeFromSuperview()
                        UIHelper.alertSimpleMessage(about: "获取客服信息失败。", withDescription: "", in: self)
                    }
                }
            }) { (error) in
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "获取客服信息失败。", withDescription: "", in: self)
                    self._loadView?.removeFromSuperview()
                }
            }
             ToolHelper.statisticsPage(pageName: "首页-底部导航-客服")
            return false
          
        case 3:
            ToolHelper.statisticsPage(pageName: "首页-底部导航-助手")
            return true
         
        case 4:
            ToolHelper.statisticsPage(pageName: "首页-底部导航-我的")
            return true
          
        default:
            break;
        }
        return true
    }
    var isStatusBarHidden = false {
        
        didSet{
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch)->Bool{
       let touchClass = NSStringFromClass((touch.view?.classForCoder)!)
        if(touchClass == "UIView"){
           return true
        }
        return false
        
    }
  @objc  public func hidenPop(){
     PopWindowHelper.closeShowCustomerServicePopView()
    }
    func showBgView()->UIView{
        let bgView :UIView  = UIView.init()
        bgView.backgroundColor = RGBAlpa(1,1,1,0.4)
        bgView.tag = 1200
        bgView.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hidenPop))
        // tapGesture.delegate = bgView.self as? UIGestureRecognizerDelegate
        tapGesture.numberOfTapsRequired = 1
        tapGesture.delegate = self
        bgView.addGestureRecognizer(tapGesture)
        return bgView
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let keywindow = UIApplication.shared.keyWindow
      
         UIApplication.shared.setStatusBarHidden(false, with: .slide)
        if kIsIpad == true {
            if (DefaultKey.modelName == "iPad Mini" || DefaultKey.modelName == "iPad Mini 2" || DefaultKey.modelName ==  "iPad Mini 3" || DefaultKey.modelName == "iPad Mini 4" || DefaultKey.modelName == "iPad Mini 5"){
                
            }else{
                let vcArr:[UIViewController] = self.viewControllers ?? []
                for index in 0 ... vcArr.count-1 {
                    let vc = vcArr[index]
                    vc.tabBarItem.imageInsets = UIEdgeInsets(top: -6, left: 0, bottom: 0, right: 0)
                }
            }
           
        }
       
        self.tabBar.tintColor = UIColor.white
        if #available(iOS 10.0, *) {
            self.tabBar.unselectedItemTintColor = UIColor.lightGray
        } else {
            // Fallback on earlier versions
        }
        self.tabBar.backgroundColor = UIColor.black
        if(UIDevice.current.isX()){
         self.tabBar.backgroundImage = UIImage(named: "tabbar_bg1")
        }else{
         self.tabBar.backgroundImage = UIImage(named: "tabbar_bg")
        }
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        self.delegate=self
    }
    
    override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        if (self.presentedViewController != nil) {
            super.dismiss(animated: flag, completion: completion)
        }
    }
    

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let idx = tabBar.items?.index(of: item)
        tabBar.tag=idx!;
        UIHelper.removeAllSubNavigation()
    }
    func flipOrientation() -> Void
    {
//        let value : Int = UIInterfaceOrientation.portrait.rawValue
//        UIDevice.current.setValue(value, forKey: "orientation")
//        UIViewController.attemptRotationToDeviceOrientation()
        DispatchQueue.main.async {
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        }
    }
    func alertCsShow(dict:[String:Any]?){
        self.effecView  = (Bundle.main.loadNibNamed("KefuView", owner: self, options: nil)![0] as! KefuView)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        window.addSubview(effecView!)
        let topDict = dict?["top"] as? [String : Any] ?? [:]
        let topStatus = topDict["status"] as? String ?? "0"
        let topTitle = topDict["title"] as? String ?? ""
     
        let bottomDict = dict?["bottom"] as? [String : Any] ?? [:]
        let bottomStatus = bottomDict["status"] as? String ?? "0"
        let bottomTitle = bottomDict["title"] as? String ?? ""

        self.effecView?.topLabel.text = topTitle
        self.effecView?.bottomLabel.text = bottomTitle
        if topStatus == "0"{
            self.effecView?.topView.isHidden = true
        }
        if bottomStatus == "0"{
            self.effecView?.bottomView.isHidden = true
        }
        effecView!.snp.makeConstraints { (make) in
            make.left.right.top.bottom.equalTo(0)
        }
     //   var alert :CsAlertView?
        print(GlobalInfo.isCallbackPhone ?? "" )
        if  GlobalInfo.isCallbackPhone == nil{
        //    alert = CsAlertView.init(title: "请选择客服");
       //    effecView!.threeButon()
        }else
        {
//            alert = CsAlertView.init(title: "请选择客服", number: GlobalInfo.isCallbackPhone!);
//            alert?.numberBtn?.addTarget(self, action: #selector(continueWithNumber(sender:)), for:.touchUpInside)
//            alert?.numbersBtn?.addTarget(self, action: #selector(continueWithNumber(sender:)), for:.touchUpInside)
        }
        weak var this = self
        effecView!.kefuclick = { type in
            switch type {
            case .HelpSelf:
                this!.continueWithSelf(sender: "")
                break
            case .kefuDownClick:
                this!.downloadAPP()
                break
                
            case .kefuOneClick:
                this!.continueWithAuto(sender: "1",dict: dict)
                break
            
            case .kefuTwoClick:
                this!.continueWithAuto(sender: "2",dict: dict)
                break
            
            case .kefuPhoneCall:
                this!.continueWithNumber(sender: "")
                break
  
            default: break
                
            }
        }
//        self.gameAlertView = alert
      //  alert?.closeBtn?.addTarget(self, action: #selector(continueWithClose), for: .touchUpInside)
     //   alert?.htmlBtn?.addTarget(self, action: #selector(continueWithSelf(sender:)), for:.touchUpInside)
    //    alert?.html5Btn?.addTarget(self, action: #selector(continueWithSelf(sender:)), for:.touchUpInside)
//        alert?.appBtn?.addTarget(self, action: #selector(continueWithAuto(sender:)), for:.touchUpInside)
//        alert?.appsBtn?.addTarget(self, action: #selector(continueWithAuto(sender:)), for:.touchUpInside)
       
//        alert.htmlImageView?.isUserInteractionEnabled = true
//        alert.appImageView?.isUserInteractionEnabled = true
//        alert.htmlImageView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(continueWithSelf(sender:))))
//        alert.appImageView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(continueWithAuto(sender:))))
//        alert?.show(target: self, animated: true)
    }
    
    func downloadAPP() {
        if (GlobalInfo.csDownClient != nil) {
             UIApplication.shared.openURL( URL(string: GlobalInfo.csDownClient!)!)
        }else{
            UIApplication.shared.openURL( URL(string: "http://down.max101.com")!)
        }
       
       
    }
    func continueWithClose(sender: Any){
        self.gameAlertView?.didTappedOnBackgroundView()
    }
    
    func continueWithSelf(sender: Any){
      print("客服信息")
        if UserHelper.getLoginStatus() {
            if GlobalInfo.isCsAuto == nil || GlobalInfo.isCsAuto == false {
                self.showToast(text: "自助客服系统暂未开放", pos:.Bottom)
                return
            }
        }else{
            self.effecView?.removeFromSuperview()
        //     self._effecView?.removeFromSuperview()
            PopWindowHelper.showLoginPopView()
             return
        }
       
        self.effecView?.removeFromSuperview()
   //     self._effecView?.removeFromSuperview()
        if UserHelper.getLoginStatus() {
            if let serviceSelfIurl=GlobalInfo.serviceSelfIurl{
                self.atcUrl=serviceSelfIurl
            }else{
                self.atcUrl="https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + "/walletm/csIndex?isMobile=1"
            }
            self.navigateWebView(toPath: self.atcUrl!, "自助客服",sign: true)
        }else{
            //    UIHelper.showRequireLoginTip(self) //已修改
            PopWindowHelper.showLoginPopView()
        }
        
        
    }
    func continueWithAuto(sender: String,dict:[String:Any]?){
        let topDict = dict?["top"] as? [String : Any] ?? [:]
        let topUrl = topDict["dropdownlist"] as? String ?? ""
        let topTitle = topDict["title"] as? String ?? ""
        let bottomDict = dict?["bottom"] as? [String : Any] ?? [:]
        let bottomUrl = bottomDict["dropdownlist"] as? String ?? ""
        let bottomTitle = bottomDict["title"] as? String ?? ""
      self.effecView?.removeFromSuperview()
        if sender == "1" {
//            if let maintainData = GlobalInfo.gameMaintainData {
//                self.csUrl = maintainData["maintain_cs_url"]!
//            }else{
//                if let siteData = GlobalInfo.siteInfoData {
//                    if let supportURL = siteData["support"] as? String {
//                        self.csUrl = supportURL
//                    }else {
//
//                        self.csUrl = GlobalInfo.defaultCSUrl
//                    }
//                }
//                if let serviceIurl=GlobalInfo.serviceIurl {
//                    self.csUrl=serviceIurl
//                }
//
//            }
//            self.navigateWebView(toPath: csUrl!, "人工客服",sign: true)
             self.navigateWebView(toPath: topUrl, topTitle,sign: true)
        }else{
//            if let serviceIurl=GlobalInfo.serviceIurlsec {
//                self.csUrl = serviceIurl
//            }else{
//                self.csUrl = GlobalInfo.defaultCS_Sec_Url
//            }
//
//             self.navigateWebView(toPath: csUrl!, "人工客服",sign: true)
            self.navigateWebView(toPath: bottomUrl, bottomTitle,sign: true)
        }
        
    }
    

    //回拨号码
    func continueWithNumber(sender: Any){
         self.effecView?.removeFromSuperview()
      //  gameAlertView?.dismiss(animated: true)
      //  self._effecView?.removeFromSuperview()
        let urlString = "tel://"+GlobalInfo.isCallbackPhone!
        if let url = URL(string: urlString) {
            //根据iOS系统版本，分别处理
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:],
                                          completionHandler: {
                                            (success) in
                })
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    func navigateWebView(toPath: String, _ title: String,sign:Bool){
        //2018.6.4 mt 改 http 改为https
       
        let goNext: WebViewController = WebViewController.init()
        goNext.url = toPath
        goNext.title = title
        //  goNext.bottomOffset = 64
        goNext.signLoging=sign
        goNext.isKefu = true
        goNext.hidesBottomBarWhenPushed = true
        funcgetCurrentViewC().navigationController?.pushViewController(goNext, animated: true)
        // goNext.hidesBottomBarWhenPushed = false
    }
    
    //移除最上层界面
    func rmTopView(){
        dismiss(animated: true, completion: nil)
    }
    
    //启动当前网络环境结束
    enum Position: Int {
        case Top
        case Mid
        case Bottom
    }
    //显示toast
    func showToast(text: String, pos: Position) {
        let rootRect = UIApplication.shared.windows.first?.frame   //应用屏幕大小
        
        let container = UIView()   //全屏且透明，盖在最上面， 可以自定义点击事件， 从而实现模态和非模态框效果。
        container.backgroundColor = UIColor.clear
        container.frame = rootRect!
        
        let lableView = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        lableView.font = UIFont.systemFont(ofSize: 15)
        lableView.textColor = UIColor.white
        lableView.text = text
        lableView.textAlignment = .center
        lableView.numberOfLines = 1
        
        let rect = lableView.getLableSize(text: text, maxWidth: 300)
        
        print("\(rect.width)  \(rect.height)")
        
        let bgView = UIView()
        bgView.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0, alpha: 0.8)
        bgView.layer.cornerRadius = 10
        var bgRect: CGRect    //黑色半透明背景
        
        switch pos {
        case .Bottom:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: (rootRect?.height)! - rect.height - 30 ,
                                     width: rect.width,
                                     height: rect.height)
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        case .Mid:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: (rootRect?.height)!/2 - rect.height/2 ,
                                     width: rect.width,
                                     height: rect.height)
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        case .Top:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: 80,
                                     width: rect.width,
                                     height: rect.height)
            
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        }
        bgView.frame = bgRect
        
        container.addSubview(bgView)
        container.addSubview(lableView)  //添加lableView
        
        let window = UIWindow()
        window.backgroundColor = UIColor.clear
        window.frame = rootRect!
        window.center = container.center
        window.windowLevel = UIWindow.Level.alert
        window.isHidden = false
        window.addSubview(container)
        
        //添加点击事件
        bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGesture(sender:))))
        
        bufWindows.append(window)
        perform(#selector(showFinished(sender:)), with: window, afterDelay: delay)
    }
    //toast超时关闭
    @objc func showFinished(sender: AnyObject) {
        if let window = sender as? UIWindow {
            if let index = bufWindows.index(of: window) {
                bufWindows.remove(at: index)  //删除
            }
        } else {
            //do nothing
        }
    }
    //添加点击事件
    @objc func tapGesture(sender: UITapGestureRecognizer) {
        
        
        //移除最后一个
        if bufWindows.count > 0 {
            bufWindows.removeLast()
        }
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }
}
extension UIDevice {
    //判断是不是 iphonex
    public func isX() -> Bool {
        if UIScreen.main.bounds.height == 812 {
            return true
        }
        return false
    }
    public func isPhone5() -> Bool {
        if UIScreen.main.bounds.height==568 {
            return true
        }
        return false
    }
    public func isPhone6s() -> Bool {
        if UIScreen.main.bounds.height==736 {
            return true
        }
        return false
    }
    
    
   
}
